/*
 * The MIT License
 *
 * Copyright 2014 Venkat Ram Akkineni.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.netbeans.modules.tfsnb.tfvc.workingfolder.treeview;

import com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Item;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.ItemSet;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.ItemType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.netbeans.modules.tfsnb.tfvc.workingfolder.treeview.nodes.BranchNodeItem;
import org.netbeans.modules.tfsnb.tfvc.workingfolder.treeview.nodes.FileItem;
import org.netbeans.modules.tfsnb.tfvc.workingfolder.treeview.nodes.FolderItem;
import org.netbeans.modules.tfsnb.tfvc.workingfolder.treeview.nodes.ItemNode;
import org.netbeans.modules.tfsnb.tfvc.workingfolder.treeview.nodes.ItemWrapper;
import org.netbeans.modules.tfsnb.tfvc.workingfolder.treeview.nodes.TeamProjectItem;

/**
 *
 * @author Venkat Ram Akkineni
 */
public class ServerItemTreeBuilder {

    private final VersionControlClient versionControlClient;
    
    public ServerItemTreeBuilder(final VersionControlClient vcc) {
        this.versionControlClient =  vcc;
    }
    
    /**
     *
     * @param itemSet
     * @return
     */
    @Deprecated
    public Map<String, ItemWrapper> getTFVCItemTree(final ItemSet itemSet) {

        final List<Item> itemList = sortItems(itemSet);

        for (final Item item : itemList) {
            System.out.println(" -> " + item.getServerItem() + "   [ " + item.getItemType() + ", " + item.isBranch() + " ]");
        }

        final Item item1 = new Item();

        final HashMap<String, ItemWrapper> itemTree = new HashMap<>();

        for (final Item item : itemList) {
            final ItemType itemType = item.getItemType();

            if (!item.getServerItem().equalsIgnoreCase("$/")) {
                if (itemType == ItemType.FOLDER) {
                    String url = item.getServerItem().substring(2);
                    String[] parts = url.split("/");

                    if (parts.length == 1) {
                        itemTree.put(parts[0], new TeamProjectItem(item));
                    } else {
                        if (item.isBranch()) {  // If there is only 
                            final BranchNodeItem branchNode = new BranchNodeItem(item);
                        } else {
                            final FolderItem folderItem = new FolderItem(item);
                        }
                    }
                    // Instantiate a FolderNode
                } else if (itemType == ItemType.FILE) {
                    // Instantiate a FileNode
                } else {
                    // Throw an unknown item type exception.
                }
            }
        }

        return itemTree;
    }

    /**
     * 
     * @param itemSet
     * @return
     * @throws org.netbeans.modules.tfsnb.tfvc.workingfolder.treeview.ServerItemTreeBuilder.UnknownFileTypeException
     * @throws org.netbeans.modules.tfsnb.tfvc.workingfolder.treeview.ServerItemTreeBuilder.IncompleteItemTreeException 
     */
    public Map<String, ItemWrapper> constructTFVCItemTree(final ItemSet itemSet) throws UnknownFileTypeException,
            IncompleteItemTreeException {
        final List<Item> itemList = sortItems(itemSet);
        final Map<String, ItemWrapper> itemTree = new HashMap<>();
        final Iterator itemIterator = itemList.listIterator();
        int currentItemListSize = 0;
        while (itemList.size() > 0) {
            while (itemIterator.hasNext()) {
                final Item item = (Item) itemIterator.next();
                boolean itemAdded = false;
                if (item.getItemType().equals(ItemType.FOLDER)) {
                    if(item.isBranch()) {
                        itemAdded = traverseAndAddItemToAppropriateNode(itemTree, new BranchNodeItem(item), item.getServerItem().split("/"));
                    } else {
                        itemAdded = traverseAndAddItemToAppropriateNode(itemTree, new FolderItem(item), item.getServerItem().split("/"));
                    }
                } else if (item.getItemType().equals(ItemType.FILE)) {
                    itemAdded = traverseAndAddItemToAppropriateNode(itemTree, new FileItem(item), item.getServerItem().split("/"));
                } else {
                    throw new UnknownFileTypeException(item);
                }

                if (itemAdded) {
                    itemIterator.remove();
                }
            }

            if (currentItemListSize == itemList.size()) {
                break;   // This is a check against infinite loop, if the 
            }                                                                // itemList size doesn't change in consecutive iterations we just exit the loop.
            currentItemListSize = itemList.size();
        }

        if (itemList.size() > 0) {
            throw new IncompleteItemTreeException("Some items recieved from the server were not added into the tree. The tree is incomplete.");
        }

        return itemTree;
    }

    /**
     * The boolean return value indicates whether or not this new ItemWrapper was added to the tree.
     *
     * The method is intended to add the last item in a url. If any directory in the provided path does not exist on the
     * tree, then this method will return false.
     *
     * i.e. If the path parts looks like this [ "home", "venkat", "Documents". "Projects", "ez-on-da-ice", "src",
     * "main", "java" ] then this method will try to add "java" directory as a child to "main" directory. And if there
     * is no node on the itemTree for "Documents" directory then this method will return false indicating that directory
     * "java" was not added to directory "main".
     *
     * @param itemTree
     * @param itemWrapper
     * @param pathParts
     * @return
     */
    protected boolean traverseAndAddItemToAppropriateNode(final Map<String, ItemWrapper> itemTree,
            final ItemWrapper itemWrapper, final String[] pathParts) {

        String[] cleanPathParts = removeEmptyElements(pathParts);

        if (itemWrapper.getItem().getItemType().equals(ItemType.FOLDER)) {
            if (itemTree.containsKey(cleanPathParts[0])) {
                if (cleanPathParts.length > 1) {
                    return traverseAndAddItemToAppropriateNode(((ItemNode) itemTree.get(cleanPathParts[0])).getChildren(), itemWrapper,
                            Arrays.copyOfRange(cleanPathParts, 1, cleanPathParts.length));
                } else {
                    return true; // The directory is already in the tree so no need to add it again. Just return true.
                }
            } else {
                if (cleanPathParts.length == 1) {
                    itemTree.put(cleanPathParts[0], itemWrapper);
                    return true;
                }
                return false;
            }
        } else if (itemWrapper.getItem().getItemType().equals(ItemType.FILE)) {
            if (itemTree.containsKey(cleanPathParts[0])) {
                if (cleanPathParts.length > 1) {
                    return traverseAndAddItemToAppropriateNode(((ItemNode) itemTree.get(cleanPathParts[0])).getChildren(), itemWrapper,
                            Arrays.copyOfRange(cleanPathParts, 1, cleanPathParts.length));
                }
            } else {
                if (cleanPathParts.length == 1) {
                    itemTree.put(cleanPathParts[0], itemWrapper);
                    return true;
                } // The directory is already in the tree so no need to add it again. Just return true.
            }
        }
        return false;
    }

    /**
     * Utility method to delete null and empty elements from a String array.
     *
     * @param pathParts
     * @return
     */
    private String[] removeEmptyElements(final String[] pathParts) {
        List<String> list = new ArrayList<>(Arrays.asList(pathParts));
        list.removeAll(Arrays.asList("", null));

        String[] result = new String[list.size()];
        return list.toArray(result);
    }

    /**
     *
     * @return
     */
    private List<Item> sortItems(final ItemSet itemSet) {
        final List<Item> sortedItems = Collections.synchronizedList(new ArrayList());
        Collections.addAll(sortedItems, itemSet.getItems());

        Collections.sort(sortedItems, new Comparator<Item>() {

            @Override
            public int compare(final Item item1, final Item item2) {
                return item1.compareTo(item2);
            }

        });

        return sortedItems;
    }

    class UnknownFileTypeException extends Exception {

        private Item item;

        public UnknownFileTypeException(final Item item) {
            super("Unknown ItemType for item: " + item.getItemID() + ", itemType: " + item.getItemType() + ", fileUrl: " + item.getServerItem());
            this.item = item;
        }

    }

    class IncompleteItemTreeException extends Exception {

        private IncompleteItemTreeException(final String msg) {
            super(msg);
        }
    }

}
